package com.acceptable.qucun.generic.security;

import com.acceptable.qucun.generic.entity.ServerItem;
import com.acceptable.qucun.generic.util.result.ResultUtil;
import com.acceptable.qucun.generic.util.result.success.UserSuccessResult;
import com.acceptable.qucun.user.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication token) throws IOException, ServletException {
        String isRemember = (String) request.getAttribute("remember_me");
        UserInfo userInfo = (UserInfo) request.getAttribute("user_info");
        if("true".equals(isRemember)) {
            userInfo.setIsRemember(true);
        }

        // 构造最终数据的结构 传给页面
        Object[] values = {userInfo, token};

        String[] keys = {"user_info", "token"};

        String res = ResultUtil.success(UserSuccessResult.LOGIN_SUCCESS, keys, values);
        response.getWriter().write(res);

    }
}
